package uk.co.richardwkirk.parkrun.web.parsers;


import java.util.LinkedList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class ParkrunWebPageParser {

	Document htmlContent = null;
	
	public ParkrunWebPageParser(String summaryPageContent) throws ParkrunDataParseException {
		// Parse the document to get the node list 
		htmlContent = Jsoup.parse(summaryPageContent);
		if (htmlContent == null) {
			throw new ParkrunDataParseException("Failed to parse parkrun page.");
		}
	}


	public Element getFirstMatchingNode(String filter) {
		// Find all the nodes that match the filter
		return getAllMatchingNodes(filter).first();
	}

	
	public Elements getAllMatchingNodes(String filter) {
		// Find all the nodes that match the filter
		return htmlContent.select(filter);
	}


	public String[][] getEventTable(int tableNumber) {
		// Get the nodes that match
		Elements tableElements = getAllMatchingNodes("table");
		if (tableElements.size() >= tableNumber) {
			// Convert the table
			return convertTable(tableElements.get(tableNumber - 1));
		}
		return new String[0][0];
	}

	private String[][] convertTable(Element tableNode) {
		List<String[]> allRows = new LinkedList<String[]>();
		Elements trElements = tableNode.select("tr");
		for (int i = 1; i < trElements.size(); ++i) {
			Elements tdElements = trElements.get(i).select("td");
			if (tdElements.size() > 0) {
				String[] row = new String[tdElements.size()];
				for (int j = 0; j < tdElements.size(); ++j) {
					row[j] = extractTextContent(tdElements.get(j));
				}
				allRows.add(row);
			}
		}
		displayTable(allRows);
		return allRows.toArray(new String[0][0]);
	}

	
	private void displayTable(List<String[]> allRows) {
		for (String[] row : allRows) {
			for (int j = 0; j < row.length; ++j) {
				System.out.print(row[j]);
				System.out.print(" | ");
			}
			System.out.println("");
		}
		
	}
	


	private String extractTextContent(Element element) {
		if (element != null && element.hasText()) {
			return element.text();
		}
		return null;
	}
	
	
	public String extractShortname(String link) {
		// e.g http://www.parkrun.org.uk/finsbury/results gives "finsbury"
		if (link != null) {
			link = link.replaceAll("http:\\/\\/", "");
			link = link.replaceAll("^[^\\/]*\\/", "");
			link = link.replaceAll("\\/.*$", "");
		}
		return link;
	}


	public String lookupLink(String text) {
		Elements allLinks = getAllMatchingNodes("a");
		for (Element link : allLinks) {
			String linkText = extractTextContent(link);
			if (text.equals(linkText)) {
				return link.attr("href");
			}
		}
		return null;
	}

}
